package entity

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//COMP_ACCO_INRT_WH
type COMP_ACCO_INRT_WH struct {
	ID    int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	JLID  int       `gorm:"column:JLID"`
	SDATE time.Time `gorm:"column:SDATE"`
	EDATE time.Time `gorm:"column:EDATE"`
	INRT  float64   `gorm:"column:INRT"`
}

//TableName
func (COMP_ACCO_INRT_WH) TableName() string {
	return "T_COMP_ACCO_INRT_WH"
}

// BeforeSave
func (u *COMP_ACCO_INRT_WH) BeforeSave(tx *gorm.DB) (err error) {
	var count int
	err = tx.Raw(`SELECT COUNT(*) FROM "T_COMP_ACCO_INRT_WH" WHERE "JLID"=? AND "EDATE"='2099-12-31'`, u.JLID).Row().Scan(&count)
	if err != nil {
		return
	}
	if count > 0 {
		var osdate time.Time
		err = tx.Raw(`SELECT MAX("SDATE") FROM "T_COMP_ACCO_INRT_WH" WHERE "JLID"=? AND "EDATE"='2099-12-31'`, u.JLID).Row().Scan(&osdate)
		if err != nil {
			return
		}
		if osdate.Unix() > u.SDATE.Unix() {
			err = fmt.Errorf("生效日期：" + u.SDATE.Format("2006-01-02") + "不能小于" + osdate.Format("2006-01-02"))
			return
		} else {
			sqlStr := `UPDATE "T_COMP_ACCO_INRT_WH" SET "EDATE"=? WHERE "JLID"=? AND "EDATE"='2099-12-31'`
			err = tx.Exec(sqlStr, u.SDATE, u.JLID).Error
			if err != nil {
				return
			}
		}
	}
	u.EDATE, _ = time.Parse("2006-01-02", "2099-12-31")
	return
}

func (u *COMP_ACCO_INRT_WH) AfterFind(tx *gorm.DB) (err error) {
	base.CHDB.Exec("system reload dictionary pas_olap_nj.DICT_COMP_ACCO_INRT_WH_ZIPPER")
	return
}

func COMP_ACCO_INRT_WHEF() base.EntityFunc {
	return func() interface{} {
		entity := COMP_ACCO_INRT_WH{}
		return &entity
	}
}
func COMP_ACCO_INRT_WHESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []COMP_ACCO_INRT_WH
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("COMP_ACCO_INRT_WH", base.NewDefaultDao(COMP_ACCO_INRT_WHEF(), COMP_ACCO_INRT_WHESF(), nil, "my"))
}
